package com.cll.learn.rpc.common.serializer;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/9/15 21:13
 */
public class ProtostuffSerializable implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(ProtostuffSerializable.class);

    @SuppressWarnings("unchecked")
    @Override
    public <T> byte[] serializable(T object) {
        logger.info("===>>> ProtostuffSerializable.serializable");
        RuntimeSchema<T> schema;
        LinkedBuffer buffer = null;
        byte[] result = null;
        try {
            schema = RuntimeSchema.createFrom((Class<T>) object.getClass());
            buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            result = ProtostuffIOUtil.toByteArray(object, schema, buffer);
        } catch (Exception e) {
            logger.error("****** 序列化异常" + e.getMessage(), e);
        } finally {
            if (null != buffer) {
                buffer.clear();
            }
        }
        return result;
    }

    @Override
    public <T> T deserializable(Class<T> clazz, byte[] byteData) {
        logger.info("===>>> ProtostuffSerializable.deserializable");
        RuntimeSchema<T> schema;
        T instance;
        try {
            schema = RuntimeSchema.createFrom(clazz);
            instance = clazz.getDeclaredConstructor().newInstance();
            ProtostuffIOUtil.mergeFrom(byteData, instance, schema);
        } catch (Exception e) {
            logger.error("****** 反序列化异常" + e.getMessage(), e);
            instance = null;
        }
        return instance;
    }
}
